<template>
    <div class="divBox">
        <el-card class="mt14" v-if="!$route.params.id">


            <router-link :to="{ path: roterPre + '/mings/list/Addroom/' }">
                <el-button type="primary" size="small" class="mb20">添加房间</el-button>
            </router-link>

            <!-- 房间列表区域 -->
            <div class="room-list">
                <div class="room-header">
                    <div class="header-item" style="width: 10%">房间ID</div>
                    <div class="header-item" style="width: 15%">房间名称</div>
                    <div class="header-item" style="width: 10%">显示状态</div>
                    <div class="header-item" style="width: 20%">封面图</div>
                    <div class="header-item" style="width: 15%">创建时间</div>
                    <div class="header-item" style="width: 20%">操作</div>
                </div>

                <div class="room-items">
                    <div v-for="(item, index) in tableData.data" :key="item.id" class="room-item">
                        <div class="item-cell" style="width: 10%">{{ item.id }}</div>
                        <div class="item-cell" style="width: 15%">{{ item.title }}</div>
                        <div class="item-cell" style="width: 10%">
                            <el-switch v-model="item.is_show" :active-value="1" :inactive-value="0" :width="55"
                                active-text="显示" inactive-text="隐藏" @change="onchangeIsShow(item)" />
                        </div>
                        <div class="item-cell" style="width: 20%">
                            <div class="room-image-container">
                                <img :src="item.mainImages[0]  || 'https://picsum.photos/300/150'" alt="房间封面图"
                                    class="room-image">
                            </div>
                        </div>
                        <div class="item-cell" style="width: 15%">{{ item.create_time }}</div>
                        <div class="item-cell" style="width: 20%">
                            <router-link :to="{ path: roterPre + '/mings/list/Addroom/' + item.id }">
                                <el-button type="text" size="small" class="mr10">编辑</el-button>
                            </router-link>
                            <el-button type="text" size="small"
                                @click="handleDelete(item.id, index)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="block">
                <el-pagination background :page-size="tableFrom.limit" :current-page="tableFrom.page"
                    layout="total, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
                    @current-change="pageChange" />
            </div>
        </el-card>

        <!-- 子路由视图 - 用于显示房间详情页 -->
        <router-view v-if="$route.params.id" />

        <!-- 添加房间弹窗 -->
        <el-dialog title="添加房间" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
            @closed="resetForm">
            <el-form ref="roomForm" :model="roomForm" :rules="rules" label-width="100px" size="small">
                <el-form-item label="房间名称" prop="room_name">
                    <el-input v-model="roomForm.room_name" placeholder="请输入房间名称" maxlength="50"
                        show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="显示状态" prop="is_show">
                    <el-switch v-model="roomForm.is_show" :active-value="1" :inactive-value="0" :width="55"
                        active-text="显示" inactive-text="隐藏"></el-switch>
                </el-form-item>
                <el-form-item label="封面图" prop="cover_img">
                    <div class="acea-row row-middle">
                        <div class="upLoadPicBox mr15" title="710*340px" @click="modalPicTap('1', 0)">
                            <div v-if="roomForm.cover_img" class="pictrue">
                                <img :src="roomForm.cover_img">
                            </div>
                            <div v-else class="upLoad">
                                <i class="iconfont iconjiahao" />
                            </div>
                        </div>
                        <div style="color: #ccc;font-size: 12px;">
                            建议尺寸710*340px
                            <el-popover placement="bottom" title="" min-width="200" trigger="hover">
                                <img :src="`${baseURL}/statics/system/topic94_01.jpg`" style="height:270px;" alt="">
                                <el-button type="text" slot="reference">查看示例</el-button>
                            </el-popover>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="roomForm.sort" :min="0" :max="999" :step="1"
                        placeholder="数字越小越靠前"></el-input-number>
                </el-form-item>
            </el-form>

            <div slot="footer">
                <el-button size="small" @click="dialogVisible = false">取消</el-button>
                <el-button size="small" type="primary" @click="submitForm">
                    确认提交
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { roomList, roomChangeStatus, roomDelete, roomAdd, roomInfo } from "@/api/mings";
import { formatDate } from "@/utils/validate";
import { roterPre } from '@/settings'
import SettingMer from '@/libs/settingMer'
export default {
    name: "RoomList",
    filters: {
        formatDate(time) {
            if (time !== 0) {
                let date = new Date(time * 1000);
                return formatDate(date, "yyyy-MM-dd hh:mm");
            }
        },
    },
    data() {
        return {
            baseURL: SettingMer.httpUrl,
            loading: false,
            roterPre: roterPre,
            tableData: {
                data: [

                ],
                total: 3,
            },
            tableFrom: {
                room_name: "",
                page: 1,
                limit: 15,
            },
            // 弹窗相关数据
            dialogVisible: false,
            fileList: [],
            roomForm: {
                room_name: '',
                is_show: 1,
                cover_img: '',
                sort: 0,
                id: 0
            },
            rules: {
                room_name: [
                    { required: true, message: '请输入房间名称', trigger: 'blur' },
                    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
                ],
                cover_img: [
                    { required: true, message: '请上传封面图片', trigger: 'change' }
                ]
            }
        };
    },
    computed: {
    },
    created() {
        this.getList();
    },
    methods: {
        /**重置搜索表单 */
        searchReset() {
            if (this.$refs.searchForm) {
                this.$refs.searchForm.resetFields()
            }
            this.getList(1)
        },
        editVisible(id) {
            this.dialogVisible = true
            // 实际项目中应该调用接口获取数据
            const room = this.tableData.data.find(item => item.id === id)
            if (room) {
                this.roomForm = JSON.parse(JSON.stringify(room))
            }
            // roomInfo(id)
            //     .then(async (res) => {
            //         this.roomForm = res.data
            //     })
            //     .catch(({ message }) => {
            //         this.$message.error(message)
            //     })
        },
        // 删除房间
        handleDelete(id, idx) {
            this.$modalSure('删除该房间').then(() => {
                // 实际项目中应该调用接口删除数据
                this.tableData.data.splice(idx, 1)
                this.tableData.total--
                roomDelete(id)
                    .then(({ message }) => {
                        this.$message.success(message)
                        this.getList(1)
                        this.tableData.total--
                    })
                    .catch(({ message }) => {
                        this.$message.error(message)
                    })
            })
        },

        // 获取房间列表
        async getList(page) {
            console.log(page, '1');
            this.loading = true;
            this.tableFrom.page = page || this.tableFrom.page;
            try {
                const params = {
                    page: this.tableFrom.page,
                    limit: this.tableFrom.limit,
                    room_name: this.tableFrom.room_name
                };
                const res = await roomList(params);
                this.tableData.data = res.data.list || [];
                this.tableData.total = res.data.count || 0;
            } catch (e) {
                this.$message.error(e.message || '获取房间列表失败');
            }
            this.loading = false;
        },
        // 分页切换
        pageChange(page) {
            this.tableFrom.page = page;
            this.getList(page);
        },
        // 每页条数变化
        handleSizeChange(val) {
            this.tableFrom.limit = val;
            this.getList(1);
        },
        // 修改显示状态
        onchangeIsShow(row) {
            // 实际项目中应该调用接口修改状态
            this.$message.success('状态修改成功');
            roomChangeStatus(row.id, row.is_show)
                .then(async (res) => {
                    this.$message.success(res.message);
                    this.getList('');
                })
                .catch((res) => {
                    this.$message.error(res.message);
                    this.getList('');
                });
        },

        // 弹窗表单相关方法
        // 重置表单
        resetForm() {
            if (this.$refs.roomForm) {
                this.$refs.roomForm.resetFields()
            }
            this.fileList = []
            this.roomForm = {
                room_name: '',
                is_show: 1,
                cover_img: '',
                sort: 0,
                id: 0
            }
        },
        // 提交添加表单
        submitForm() {
            this.$refs.roomForm.validate(async (valid) => {
                if (valid) {
                    try {
                        // 实际项目中应该调用接口添加数据
                        if (this.roomForm.id) {
                            // 编辑
                            const index = this.tableData.data.findIndex(item => item.id === this.roomForm.id)
                            if (index !== -1) {
                                this.tableData.data[index] = JSON.parse(JSON.stringify(this.roomForm))
                            }
                            this.$message.success('编辑成功')
                        } else {
                            // 新增
                            const newRoom = JSON.parse(JSON.stringify(this.roomForm))
                            newRoom.id = this.tableData.data.length + 1
                            newRoom.create_time = new Date().toLocaleString()
                            this.tableData.data.unshift(newRoom)
                            this.tableData.total++
                            this.$message.success('添加成功')
                        }
                        this.dialogVisible = false
                        // const { message } = await roomAdd(this.roomForm)
                        // this.$message.success(message)
                        // this.dialogVisible = false
                        // 重新获取列表数据
                        // this.getList(1)
                    } catch (error) {
                        this.$message.error(error.message || '操作失败')
                    }
                }
            })
        },
        modalPicTap(tit, num, i) {
            const _this = this;
            this.$modalUpload(function (img) {
                _this.roomForm.cover_img = img[0];
            }, tit);
        },
        goToDetail(id) {
            this.$router.push({ path: `/merchant/mings/list/title/${id}` });
        },
        addRoom() {
            this.$router.push({ path: '/merchant/mings/list/title/new' });
        },
    },
};
</script>

<style scoped lang="scss">
/* 房间列表样式 */
.room-list {
    margin-bottom: 20px;
    overflow-x: auto;

    .room-header {
        display: flex;
        background-color: #f5f7fa;
        border-radius: 4px 4px 0 0;
        padding: 10px 0;
        font-weight: bold;

        .header-item {
            padding: 0 10px;
            text-align: center;
        }
    }

    .room-items {
        .room-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #ebeef5;
            transition: background-color 0.2s;

            &:hover {
                background-color: #f9fafc;
            }

            .item-cell {
                padding: 0 10px;
                text-align: center;

                .room-image-container {
                    width: 100%;
                    height: 80px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    overflow: hidden;
                    border-radius: 4px;

                    .room-image {
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: cover;
                    }
                }
            }
        }
    }
}

/* 基础样式 */
.divBox {
    padding: 15px;
}

.selCard {
    background: #fff;
    margin-bottom: 15px;
    border-radius: 4px;
}

.selWidth {
    width: 180px;
}

.mt14 {
    margin-top: 14px;
}

.mb20 {
    margin-bottom: 20px;
}

.mr10 {
    margin-right: 10px;
}

.block {
    padding: 20px;
    text-align: right;
}

/* 上传组件样式 */
.upLoadPicBox {
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: inline-block;
    line-height: 1;
}

.upLoadPicBox .pictrue {
    width: 100%;
    height: 100%;
    position: relative;
}

.upLoadPicBox .pictrue img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.upLoadPicBox .upLoad {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.upLoadPicBox .upLoad .iconjiahao {
    font-size: 28px;
    color: #8c939d;
}
</style>
